import { getDstPSAppDEAction, IPSDEUIDEActionLogic, IPSDEUILogicParam } from '@ibiz/dynamic-model-api';
import { LogUtil, Util } from 'ibiz-core';
import { UIActionContext } from '../uiaction-context';
import { AppUILogicNodeBase } from './logic-node-base';
/**
 * 实体行为调用节点
 *
 * @export
 * @class AppUILogicDeactionNode
 */
export class AppUILogicDeactionNode extends AppUILogicNodeBase {

    constructor() {
        super();
    }

    /**
     * 执行节点
     *
     * @param {IPSDEUIDEActionLogic} logicNode 逻辑节点模型数据
     * @param {UIActionContext} actionContext 界面逻辑上下文
     * @memberof AppUILogicDeactionNode
     */
    public async executeNode(logicNode: IPSDEUIDEActionLogic, actionContext: UIActionContext) {
        try {
            await this.handleDEAction(logicNode, actionContext);
            return this.computeNextNodes(logicNode, actionContext);
        } catch (error: any) {
            LogUtil.error(`逻辑节点${logicNode.name}${error?.message ? error?.message : '发生未知错误！'}`);
        }
    }

    /**
     * 处理实体行为
     *
     * @private
     * @param {IPSDEUIDEActionLogic} logicNode 逻辑节点模型数据
     * @param {UIActionContext} actionContext 界面逻辑上下文
     * @memberof AppUILogicDeactionNode
     */
    private async handleDEAction(logicNode: IPSDEUIDEActionLogic, actionContext: UIActionContext) {
        const dstEntity = logicNode.getDstPSAppDataEntity();
        const deAction = await getDstPSAppDEAction(logicNode);
        const dstParam = actionContext.getParam((logicNode.getDstPSDEUILogicParam() as IPSDEUILogicParam)?.codeName);
        const retParam = actionContext.getParam((logicNode.getRetPSDEUILogicParam() as IPSDEUILogicParam)?.codeName);
        if (dstEntity && deAction && dstParam) {
            try {
                const service = await ___ibz___.gs.getService(dstEntity.codeName);
                const tempContext = Util.deepCopy(actionContext.context);
                if(dstParam.getReal()){
                    Object.assign(tempContext, dstParam.getReal());
                }
                const res = await service[deAction.codeName](tempContext, dstParam.getReal() ? dstParam.getReal() : {});
                if (res) {
                    if (res.ok) {
                        if (res.data) {
                            // 返回绑定参数可能没有
                            if(retParam){
                                retParam.bind(res.data);
                            }
                            actionContext.bindLastReturnParam(res.data);
                        }
                    }
                    return retParam;
                } else {
                    throw new Error(`调用实体行为异常`);
                }
            } catch (error: any) {
                throw new Error(`调用实体行为异常${error?.message ? error.message : ''}`);
            }
        } else {
            throw new Error(`调用实体行为参数不足`);
        }
    }
}